package com.cjgl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjgl.common.ErrorCode;
import com.cjgl.exception.BusinessException;
import com.cjgl.mapper.TblUsersMapper;
import com.cjgl.model.entity.TblUsers;
import com.cjgl.service.TblUsersService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.cjgl.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author zhangyuwu
 * @description 针对表【tbl_users(用户信息表)】的数据库操作Service实现
 * @createDate 2023-05-24 13:49:32
 */
@Service
public class TblUsersServiceImpl extends ServiceImpl<TblUsersMapper, TblUsers>
		implements TblUsersService {

	private static final String SALT = "wzy";
	@Resource
	TblUsersMapper usersMapper;

	/**
	 * 用户登录
	 *
	 * @param userNo
	 * @param userPassword
	 * @param request
	 * @return
	 */
	@Override
	public Boolean userLogin(String userNo, String userPassword, HttpServletRequest request) {
		QueryWrapper<TblUsers> tblUsersQueryWrapper = new QueryWrapper<>();
		if (StringUtils.isAllEmpty(userNo, userPassword)) {
			throw new BusinessException(ErrorCode.PARAMS_ERROR);
		}
		tblUsersQueryWrapper.eq("userNo", userNo);
		//加密
		//String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
		tblUsersQueryWrapper.eq("userPassword", userPassword);
		TblUsers tblUsers = baseMapper.selectOne(tblUsersQueryWrapper);
		if (tblUsers == null) {
			throw new BusinessException(ErrorCode.PARAMS_ERROR);
		}
		request.getSession().setAttribute(USER_LOGIN_STATE, tblUsers);
		return true;
	}

	/**
	 * 获取当前登录用户
	 *
	 * @param request
	 * @return
	 */
	@Override
	public TblUsers getLoginUser(HttpServletRequest request) {
		// 先判断是否已登录
		Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
		TblUsers currentUser = (TblUsers) userObj;
		if (currentUser == null || currentUser.getId() == null) {
			throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
		}
		// 从数据库查询（追求性能的话可以注释，直接走缓存）
		long userId = currentUser.getId();
		currentUser = this.getById(userId);
		if (currentUser == null) {
			throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
		}
		return currentUser;
	}

	@Override
	public int changeUserPassword(String userNo, String userPassword) {


		//检查参数
		if (StringUtils.isAllEmpty(userNo, userPassword)) {
			throw new BusinessException(ErrorCode.PARAMS_ERROR);
		}

		TblUsers tblUser = new TblUsers();
		tblUser.setUserNo(userNo);
		tblUser.setUserPassword(userPassword);

		Integer passWordIsChanged = usersMapper.updateUserPasswordByUserNo(userNo, userPassword);
		return passWordIsChanged;
	}
}




